import React, { useEffect } from 'react';
import Loadable from 'react-loadable';
import { useLocation } from 'react-router-dom';
import { useAppDispatch } from '@store/hooks';

import * as headerSlice from '@store/reducers/headerSlice';
import * as breadSlice from '@store/reducers/breadSlice';
import * as leftSiderSlice from '@store/reducers/leftSiderSlice';
import * as footerSlice from '@store/reducers/footerSlice';

//通用的过场组件
const loadingComponent = () => {
    return <div>loading...</div>;
};

export const LoadComponent = (component: { (): Promise<any>; (): Promise<any> }, loading = loadingComponent) =>
    Loadable({
        loader: component,
        loading: loading,
    });

//Ele: React.ComponentType<unknown> & Loadable.LoadableComponent,
const LoadPage = (component: { (): Promise<any>; (): Promise<any> }, opts: RouterItem) => {
    return function Page() {
        // console.log('page');
        const location = useLocation();
        const dispatch = useAppDispatch();
        let pathname = location.pathname;

        let header: Header = opts.header || { hidden: false };
        let footer: Footer = opts.footer || { hidden: false };
        let leftSide: LeftSide = opts.leftSide || { hidden: false };
        let bread: Bread = opts.bread || { hidden: false };

        useEffect(() => {
            dispatch(headerSlice.setOption(header));
            dispatch(breadSlice.setOption(bread));
            dispatch(leftSiderSlice.setOption(leftSide));
            dispatch(footerSlice.setOption(footer));
            dispatch(leftSiderSlice.setSelectedKeys([pathname]));
        }, []);

        const Element = LoadComponent(component, loadingComponent);
        return <Element></Element>;
    };
};

export default LoadPage;
